import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:video_player/video_player.dart';
import '../services/alger_api_service.dart';
import '../utils/util.dart';

class AlgerMvPlayerScreen extends StatefulWidget {
  final String mvId;
  final String mvName;
  final String coverUrl;
  final String? mvUrl; // 可直接传入完整播放地址（含 wsSecret/wsTime）
  const AlgerMvPlayerScreen({super.key, required this.mvId, required this.mvName, required this.coverUrl, this.mvUrl});

  @override
  State<AlgerMvPlayerScreen> createState() => _AlgerMvPlayerScreenState();
}

class _AlgerMvPlayerScreenState extends State<AlgerMvPlayerScreen> {
  final AlgerApiService _api = AlgerApiService();
  String? _mvUrl;
  bool _loading = true;
  String? _error;
  VideoPlayerController? _controller;
  bool _muted = false;
  bool _isInitializing = false;
  bool _showBigPlay = true;

  @override
  void initState() {
    super.initState();
    _fetchUrl();
  }

  Future<void> _fetchUrl() async {
    setState(() {
      _loading = true;
      _error = null;
      _mvUrl = null;
    });
    try {
      // 若直接传入了 mvUrl，优先使用
      final preset = _normalizeUrl(widget.mvUrl);
      if (preset != null && preset.isNotEmpty) {
        setState(() => _mvUrl = preset);
        await _initPlayer(preset);
      } else {
        final urlRaw = await _api.fetchMvUrl(widget.mvId);
        final url = _normalizeUrl(urlRaw);
        setState(() => _mvUrl = url);
        if (url != null && url.isNotEmpty) {
          await _initPlayer(url);
        }
      }
    } catch (e) {
      setState(() => _error = '获取播放地址失败: $e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _initPlayer(String url) async {
    print('[MV播放器] 初始化播放器 url $url');
    // 释放旧控制器
    await _controller?.dispose();
    setState(() => _isInitializing = true);
    final ctrl = VideoPlayerController.networkUrl(Uri.parse(_normalizeUrl(url)!));
    _controller = ctrl;
    try {
      await ctrl.initialize();
      ctrl.setLooping(false);
      setState(() {});
    } catch (e) {
      setState(() => _error = '播放器初始化失败: $e');
    }
    if (mounted) setState(() => _isInitializing = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.mvName),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 播放器区域（占据剩余空间，保证下方按钮与提示始终可见）
              Expanded(
                child: Center(
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: AspectRatio(
                      aspectRatio: _controller?.value.isInitialized == true
                          ? (_controller!.value.aspectRatio <= 0 ? 16 / 9 : _controller!.value.aspectRatio)
                          : 16 / 9,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          // 底层：视频或封面
                          if (_controller?.value.isInitialized == true)
                            VideoPlayer(_controller!)
                          else if (widget.coverUrl.isNotEmpty)
                            CachedNetworkImage(imageUrl: widget.coverUrl, fit: BoxFit.cover)
                          else
                            Container(color: Colors.grey[200]),

                          // 中间：初始化指示器
                          if (_isInitializing)
                            const Center(child: CircularProgressIndicator()),

                          // 中间：大播放按钮（未初始化或未播放时显示）
                          if (_showBigPlay && !_isInitializing && (_controller == null || !_controller!.value.isInitialized || !_controller!.value.isPlaying))
                            Center(
                              child: ElevatedButton.icon(
                                style: ElevatedButton.styleFrom(backgroundColor: Colors.black54, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10)),
                                onPressed: () async {
                                  // 如果还没有地址，先获取；否则初始化或直接播放
                                  final url = _mvUrl;
                                  if (_controller == null || !_controller!.value.isInitialized) {
                                    if (url == null || url.isEmpty) {
                                      await _fetchUrl();
                                    } else {
                                      await _initPlayer(url);
                                    }
                                  } else {
                                    await _controller!.play();
                                    setState(() {});
                                  }
                                  setState(() => _showBigPlay = false);
                                },
                                icon: const Icon(Icons.play_arrow, size: 24),
                                label: const Text('播放'),
                              ),
                            ),

                          // 底部：控制条（已初始化后显示）
                          if (_controller?.value.isInitialized == true)
                            Align(
                              alignment: Alignment.bottomCenter,
                              child: _buildControls(),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildControls() {
    final ctrl = _controller;
    if (ctrl == null) return const SizedBox.shrink();
    final isPlaying = ctrl.value.isPlaying;
    return Container(
      color: Colors.black.withOpacity(0.25),
      height: 40,
      child: Row(
        children: [
          IconButton(
            icon: Icon(isPlaying ? Icons.pause : Icons.play_arrow, color: Colors.white),
            onPressed: () async {
              if (isPlaying) {
                await ctrl.pause();
              } else {
                await ctrl.play();
              }
              setState(() {});
            },
          ),
          IconButton(
            icon: Icon(_muted ? Icons.volume_off : Icons.volume_up, color: Colors.white),
            onPressed: () async {
              _muted = !_muted;
              await ctrl.setVolume(_muted ? 0.0 : 1.0);
              setState(() {});
            },
          ),
          const SizedBox(width: 8),
          Expanded(
            child: VideoProgressIndicator(
              ctrl,
              allowScrubbing: true,
              colors: VideoProgressColors(playedColor: Colors.blueAccent, bufferedColor: Colors.white70, backgroundColor: Colors.black38),
            ),
          ),
          const SizedBox(width: 8),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  // 规范化 URL：去除换行/空格，修复被断行的查询参数
  String? _normalizeUrl(String? raw) {
    if (raw == null) return null;
    final s = raw.replaceAll(RegExp(r"\s+"), "");
    // 简单修复部分接口可能返回的双问号或多余 &
    final fixed = s
        .replaceAll('??', '?')
        .replaceAll(RegExp(r'&{2,}'), '&');
    return fixed;
  }
}
